import { Extension } from '@tiptap/core'

export const LineHeight = Extension.create({
	name: 'lineHeight',

	addOptions() {
		return {
			types: ['paragraph', 'heading', 'list_item'],
			lineHeights: ['1.0', '1.5', '2.0', '2.5', '3.0']
		}
	},

	addGlobalAttributes() {
		return [
			{
				types: this.options.types,
				attributes: {
					lineHeight: {
						default: null,
						parseHTML: element => element.style.lineHeight?.replace(/['"]+/g, '') || null,
						renderHTML: attributes => {
							if (!attributes.lineHeight) {
								return {}
							}
							return { style: `line-height: ${attributes.lineHeight}` }
						}
					}
				}
			}
		]
	},

	addCommands() {
		return {
			setLineHeight:
				lineHeight =>
				({ commands }) => {
					return commands.updateAttributes('paragraph', { lineHeight })
				},
			unsetLineHeight:
				() =>
				({ commands }) => {
					return commands.resetAttributes('paragraph', 'lineHeight')
				}
		}
	},

	addKeyboardShortcuts() {
		return {
			'Mod-Shift-1': () => this.editor.commands.setLineHeight('1.0'),
			'Mod-Shift-2': () => this.editor.commands.setLineHeight('2.0')
		}
	}
})
